import React, { useState, useEffect } from 'react';
import { 
  Row, 
  Col, 
  Card, 
  Typography, 
  Button, 
  List, 
  Tag, 
  Statistic, 
  Empty, 
  Space, 
  Divider,
  Modal
} from 'antd';
import { 
  RightOutlined, 
  ClockCircleOutlined, 
  TrophyOutlined,
  CodeOutlined, 
  FireOutlined,
  TeamOutlined,
  BookOutlined,
  BarChartOutlined,
  CalendarOutlined,
  LikeOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { contestService } from '@/services/contestService';
import { Contest } from '@/types/contest';
import styles from './index.module.css';

const { Title, Paragraph, Text } = Typography;



// 模拟数据 - 快速入口
const quickAccessData = [
  { 
    id: 1, 
    title: '每日一题', 
    icon: <FireOutlined />, 
    description: '每天练习一题，进步看得见', 
    link: '#' 
  },
  { 
    id: 2, 
    title: '题目列表', 
    icon: <BookOutlined />, 
    description: '浏览所有题目，按难度和类型筛选', 
    link: '/problem/list' 
  },
  { 
    id: 3, 
    title: '比赛中心', 
    icon: <TrophyOutlined />, 
    description: '参加各类编程比赛，提升实战能力', 
    link: '/contest/list' 
  },
  { 
    id: 4, 
    title: '学习路径', 
    icon: <BarChartOutlined />, 
    description: '系统化学习，从新手到大师', 
    link: '/learn/path' 
  }
];

// 移除模拟的比赛数据，改为从API获取

const ClientHomePage: React.FC = () => {
  const navigate = useNavigate();
  const [contests, setContests] = useState<Contest[]>([]);
  const [contestsLoading, setContestsLoading] = useState(false);
  const [userStats, setUserStats] = useState({
    solvedProblems: 42,
    contestsJoined: 7,
    ranking: 158,
    streak: 5
  });
  
  // 运势抽签相关状态
  const [fortuneResult, setFortuneResult] = useState<any>(null);
  const [isDrawing, setIsDrawing] = useState(false);

  // 获取进行中和即将开始的比赛
  const fetchContests = async () => {
    try {
      setContestsLoading(true);
      const response = await contestService.getContests();
      const allContests = response.data.data || [];
      
      // 筛选进行中(status: '0')和即将开始(status: '1')的比赛
      const activeContests = allContests.filter(contest => 
        contest.status === '0' || contest.status === '1'
      );
      
      // 按开始时间排序，即将开始的排在前面
      const sortedContests = activeContests.sort((a, b) => {
        if (a.status === '0' && b.status === '1') return -1; // 进行中的排在前面
        if (a.status === '1' && b.status === '0') return 1;
        return new Date(a.start_time).getTime() - new Date(b.start_time).getTime();
      });
      
      setContests(sortedContests);
    } catch (error) {
      console.error('获取比赛列表失败:', error);
    } finally {
      setContestsLoading(false);
    }
  };

  // 获取比赛状态标签
  const getContestStatusTag = (status: string) => {
    if (status === '1') {
      return <Tag color="blue">即将开始</Tag>;
    } else if (status === '0') {
      return <Tag color="green">进行中</Tag>;
    } else {
      return <Tag color="gray">已结束</Tag>;
    }
  };

  // 格式化时间显示
  const formatDateTime = (dateTimeString: string) => {
    const date = new Date(dateTimeString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 这里可以添加获取真实数据的逻辑
  useEffect(() => {
    // 从API获取数据
    fetchContests();
  }, []);



  // 处理点击快速入口
  const handleQuickAccessClick = (link: string) => {
    navigate(link);
  };

  // 导航到比赛详情
  const goToContestDetail = (contestId: number) => {
    navigate(`/contest/${contestId}`);
  };

  // 导航到题目详情
  const goToProblemDetail = (problemId: number) => {
    navigate(`/problem/detail/${problemId}`);
  };

  // 运势抽签相关函数
  const getTodayKey = () => {
    const today = new Date();
    return `fortune_${today.getFullYear()}_${today.getMonth() + 1}_${today.getDate()}`;
  };

  const loadTodayFortune = () => {
    const todayKey = getTodayKey();
    const savedFortune = localStorage.getItem(todayKey);
    if (savedFortune) {
      try {
        const fortune = JSON.parse(savedFortune);
        setFortuneResult(fortune);
      } catch (error) {
        console.error('Failed to parse saved fortune:', error);
        localStorage.removeItem(todayKey);
      }
    }
  };

  const saveTodayFortune = (fortune: any) => {
    const todayKey = getTodayKey();
    localStorage.setItem(todayKey, JSON.stringify(fortune));
  };

  const drawFortune = () => {
    setIsDrawing(true);
    
    // 模拟抽签动画
    setTimeout(() => {
      const fortunes = [
        {
          level: '大吉',
          color: '#52c41a',
          emoji: '🎉',
          message: '今日编程运势极佳！适合挑战高难度题目，比赛成绩有望突破！',
          advice: '建议尝试一些算法竞赛题目，今天的学习效率会很高。',
          luckyNumbers: [1, 8, 15, 22, 29],
          luckyAlgorithms: ['动态规划', '贪心算法', '分治算法'],
          luckyTopics: ['图论', '字符串', '数学']
        },
        {
          level: '中吉',
          color: '#1890ff',
          emoji: '✨',
          message: '今日编程运势不错，学习状态良好！',
          advice: '可以复习一下基础算法，巩固知识点。',
          luckyNumbers: [2, 9, 16, 23, 30],
          luckyAlgorithms: ['深度优先搜索', '广度优先搜索', '二分查找'],
          luckyTopics: ['数组', '链表', '栈和队列']
        },
        {
          level: '小吉',
          color: '#faad14',
          emoji: '🌟',
          message: '今日编程运势平稳，适合稳步前进。',
          advice: '建议做一些中等难度的题目，保持学习节奏。',
          luckyNumbers: [3, 10, 17, 24, 31],
          luckyAlgorithms: ['排序算法', '查找算法', '递归'],
          luckyTopics: ['树', '哈希表', '堆']
        },
        {
          level: '平',
          color: '#8c8c8c',
          emoji: '📚',
          message: '今日编程运势一般，需要更加努力。',
          advice: '建议多练习基础题目，打好基础很重要。',
          luckyNumbers: [4, 11, 18, 25, 32],
          luckyAlgorithms: ['暴力枚举', '模拟', '前缀和'],
          luckyTopics: ['基础语法', '循环', '条件判断']
        },
        {
          level: '小凶',
          color: '#fa8c16',
          emoji: '💪',
          message: '今日编程运势稍差，但不要气馁！',
          advice: '建议从简单题目开始，慢慢找回状态。',
          luckyNumbers: [5, 12, 19, 26, 33],
          luckyAlgorithms: ['简单模拟', '基础循环', '数组操作'],
          luckyTopics: ['变量', '数据类型', '运算符']
        },
        {
          level: '大凶',
          color: '#f5222d',
          emoji: '🔥',
          message: '今日编程运势不佳，但逆境中成长最快！',
          advice: '建议多休息，调整心态，明天会更好！',
          luckyNumbers: [6, 13, 20, 27, 34],
          luckyAlgorithms: ['休息', '调整心态', '基础练习'],
          luckyTopics: ['放松', '复习', '总结']
        }
      ];
      
      const randomFortune = fortunes[Math.floor(Math.random() * fortunes.length)];
      setFortuneResult(randomFortune);
      saveTodayFortune(randomFortune);
      setIsDrawing(false);
    }, 2000);
  };

  // 页面加载时检查今日运势
  useEffect(() => {
    loadTodayFortune();
  }, []);

  return (
    <div className={styles.homePage}>
      <Row gutter={[24, 24]} className={styles.contentSection}>
        {/* 左侧内容 */}
        <Col xs={24} md={12}>
          {/* 快速入口 */}
          <div className={styles.quickAccessSection}>
            <div className={styles.sectionHeader}>
              <Title level={4}>快速入口</Title>
              <Text type="secondary">选择您想要进行的活动</Text>
            </div>
            <Row gutter={[16, 16]}>
              {quickAccessData.map(item => (
                <Col xs={24} sm={12} key={item.id}>
                  <Card 
                    hoverable 
                    className={styles.quickAccessCard}
                    onClick={() => handleQuickAccessClick(item.link)}
                  >
                    <div className={styles.quickAccessIcon}>
                      {item.icon}
                    </div>
                    <div className={styles.quickAccessContent}>
                      <Title level={5}>{item.title}</Title>
                      <Text type="secondary">{item.description}</Text>
                    </div>
                  </Card>
                </Col>
              ))}
            </Row>
          </div>

          {/* 用户统计信息 */}
          <Card className={styles.statsCard} title="我的学习统计">
            <Row gutter={[16, 16]}>
              <Col span={12}>
                <Statistic 
                  title="已解决题目" 
                  value={userStats.solvedProblems} 
                  prefix={<CodeOutlined />} 
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="参与比赛" 
                  value={userStats.contestsJoined} 
                  prefix={<TrophyOutlined />} 
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="当前排名" 
                  value={userStats.ranking} 
                  prefix={<BarChartOutlined />} 
                />
              </Col>
              <Col span={12}>
                <Statistic 
                  title="连续打卡" 
                  value={userStats.streak} 
                  prefix={<FireOutlined />} 
                  suffix="天" 
                />
              </Col>
            </Row>
            <Divider />
            <div className={styles.statsFooter}>
              <Button type="primary" block onClick={() => navigate('/profile/stats')}>
                查看完整统计
              </Button>
            </div>
          </Card>
        </Col>

        {/* 右侧边栏 */}
        <Col xs={24} md={12}>
          {/* 运势抽签 */}
          <Card className={styles.fortuneCard} title="今日运势">
            <div className={styles.fortuneContent}>
              {!fortuneResult ? (
                <>
                  <div className={styles.fortuneIcon}>🎯</div>
                  <div className={styles.fortuneText}>
                    <p>点击下方按钮，抽取今日编程运势</p>
                    <Button 
                      type="primary" 
                      onClick={drawFortune}
                      loading={isDrawing}
                      className={styles.fortuneButton}
                    >
                      {isDrawing ? '抽签中...' : '抽签'}
                    </Button>
                  </div>
                </>
              ) : (
                <div className={styles.fortuneResult}>
                  <div className={styles.fortuneResultHeader}>
                    <div 
                      className={styles.fortuneLevel}
                      style={{ color: fortuneResult.color }}
                    >
                      {fortuneResult.emoji} {fortuneResult.level}
                    </div>
                  </div>
                  <div className={styles.fortuneResultContent}>
                    <p className={styles.fortuneMessage}>{fortuneResult.message}</p>
                    <div className={styles.fortuneAdvice}>
                      <strong>学习建议：</strong>
                      <p>{fortuneResult.advice}</p>
                    </div>
                    <div className={styles.fortuneDetails}>
                      <div className={styles.fortuneDetailItem}>
                        <strong>幸运数字：</strong>
                        <span>{fortuneResult.luckyNumbers.join(', ')}</span>
                      </div>
                      <div className={styles.fortuneDetailItem}>
                        <strong>推荐算法：</strong>
                        <span>{fortuneResult.luckyAlgorithms.join('、')}</span>
                      </div>
                      <div className={styles.fortuneDetailItem}>
                        <strong>学习主题：</strong>
                        <span>{fortuneResult.luckyTopics.join('、')}</span>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </Card>

          {/* 近期比赛 */}
          <Card 
            className={styles.contestCard} 
            title="近期比赛"
            extra={
              <Button type="link" onClick={() => navigate('/contest/list')}>
                查看全部 <RightOutlined />
              </Button>
            }
          >
            <div className={styles.contestContent}>
              <List
                className={styles.contestList}
                dataSource={contests}
                loading={contestsLoading}
                locale={{
                  emptyText: '暂无进行中或即将开始的比赛'
                }}
                renderItem={contest => (
                  <List.Item 
                    key={contest.id}
                    onClick={() => goToContestDetail(contest.id)}
                    className={styles.contestItem}
                  >
                    <div className={styles.contestInfo}>
                      <div className={styles.contestTitle}>
                        {contest.title}
                        {getContestStatusTag(contest.status)}
                      </div>
                      <div className={styles.contestTime}>
                        <ClockCircleOutlined /> {formatDateTime(contest.start_time)} - {formatDateTime(contest.end_time)}
                      </div>
                      <div className={styles.contestParticipants}>
                        <TeamOutlined /> {contest.rule_type} 规则
                      </div>
                    </div>
                    <Button type="primary" ghost>
                      查看详情
                    </Button>
                  </List.Item>
                )}
              />
            </div>
          </Card>
        </Col>
      </Row>

      {/* 学习建议区域 */}
      <div className={styles.suggestionsSection}>
        <Card className={styles.suggestionsCard}>
          <Title level={4}>学习建议</Title>
          <Paragraph>
            <ul className={styles.suggestionsList}>
              <li>
                <LikeOutlined /> 每天坚持解决至少一道编程题目，培养编程思维
              </li>
              <li>
                <CalendarOutlined /> 定期参加比赛，在实战中检验和提升自己的能力
              </li>
              <li>
                <BookOutlined /> 系统学习算法与数据结构，掌握解题的核心方法
              </li>
              <li>
                <TeamOutlined /> 加入学习小组，与同学一起讨论和进步
              </li>
            </ul>
          </Paragraph>
        </Card>
      </div>


    </div>
  );
};

export default ClientHomePage;
